<?php
require_once(APPPATH.'libraries/MY_PortalController.php');
class Player extends MY_PortalController {

	function Player()
	{
		parent::MY_PortalController();
	}

	function load_main_page($pc_type){

		//Controlo que el usuario este logueado
		$user = $this->getUserLogued();

		if($user == NULL){
			redirect("/main/". $pc_type);
			return;
		}

		$this->setPCType($pc_type);
		$this->load->model('m_channel');
		$this->load->model('m_user');

		$channel = $this->m_channel->getChannelByUser($user->id);

		$ok=true;
		if($channel==null){
			//Si no existe el canal asociado al usuario este es creado
			try{
				$this->db->trans_begin();
				//Channel
				$channel = $this->createChannelForUser($user);
				$this->db->trans_commit();
			}catch(Exception $e){
				$this->db->trans_rollback();
				$msg = $e->getMessage();
				$ok=false;
			}
		}

		if($ok){
			//Preferencias de usuario
			$this->load->model('m_user_preferencias');
			$upref = $this->m_user_preferencias->getPref($user->id,"PLAYLIST_PATH");
			$playlist_path = $upref==NULL ? "":$upref->value;
			//
			$data = array(
				"user"			=> $user,
				"channel_id"	=> $channel->id,
				"channel_name"	=> $channel->name,
				"channel_dsc"	=> $channel->description,
				"tracker_url"	=> $channel->tracker_url,
				"prefs"			=> array("playlist_path"=>$playlist_path)
			);

			/////////////////////////////
			$data["pc_type"] = $this->getPCType();
			if($channel->active==1){
				$user_ip = $_SERVER["REMOTE_ADDR"];
				try{
					$this->load_api();
					$suite_data = $this->api->get_web_broadcast_data($channel->suite_id, $user->id, $user_ip );
					$data["broadcast_data"]["controller_url"] = $suite_data["controller_url"];
					$data["broadcast_data"]["certificates_url"] = $suite_data["certificates_url"];
					$data['broadcast_data']["xmltv_id"] = $suite_data['xmltv_id'];
				}catch(GoalbitServicesAPIException $error){
					$this->showError($error->get_message());
					return;
				}
			}
			$this->load->view('main',$data);
		}else{
			$this->showError($msg);
		}
	}

	function modify_channel(){

		//Controlo que el usuario este logueado
		$user = $this->getUserLogued();
		if($user == NULL){
			redirect("/main/". $this->input->post('pc_type'));
			return;
		}
		
		$ret = array();
		$ok = true;
		$msg = "Modificado con exito!";

		$this->load->model('m_channel');
		$channel = $this->m_channel->getChannelByUser($user->id);
		if($channel==null){
			$ok = false;
			$msg = "No se encontro un canal asociado al usuario";
		}else{
			$channel->name			= $_REQUEST['name'];
			$channel->description	= $_REQUEST['dsc'];
			try{
				$this->db->trans_begin();
				$this->m_channel->update($channel);
				$this->db->trans_commit();
			}catch(Exception $e){
				$this->db->trans_rollback();
				$ok = false;
				$msg = $e->getMessage();
			}
		}

		$this->returnJson(array("ok"=>$ok,"msg"=>$msg));
	}
	
	function find_channels(){
		$this->load->model('m_channel');

		$search = $this->input->post('busqueda');
		$page = $this->input->post('page');
		$page_ceibal = $this->input->post('page_ceibal');

		$channel_data = $this->getSerchedCahnnels($page,$search,8,0);
		$ceibal_channel_data = $this->getSerchedCahnnels($page_ceibal,$search,4,1);

		$data = array
		(
			"data" 	=> $channel_data,
			"ceibal_data"	=> $ceibal_channel_data
		);
		
		$this->load->view('search_channels',$data);
	}

	function get_streaming_url($channel_id){
		$ret = array(
			'ok' => true,
			'msg'=>''
		);
		$this->load->model('m_channel');
		$channel = $this->m_channel->getByChannelId($channel_id);
		if($channel==null){
			$ret['ok'] = false;
			$ret['msg'] = "No se encontro un canal";
		}else{
			try{
				$this->load_api();
				$user_ip = $_SERVER['REMOTE_ADDR'];
				$resp = $this->api->get_streaming_url($channel->suite_id, $user_ip);
				$ret['url'] = $resp['url'];
			}catch ( GoalbitServicesAPIException $error ){
				$ret['ok'] = false;
				$ret['msg'] = "Ah ocurrido un error de conexion interno: " . $error->getMessage();
			}
		}
		$this->returnJson($ret);
	}

	function setUserPreferences(){

		$ret = array('ok' => true,'msg'=>'');

		//Controlo que el usuario este logueado
		$user = $this->getUserLogued();
		if($user == NULL){
			$this->returnJson(array('ok' => false,'msg'=>'No permitido'));
			return;
		}

		$name = $this->input->post('name');
		$value = $this->input->post('value');

		//Preferencias de usuario
		try{
			$this->load->model('m_user_preferencias');
			$upref = $this->m_user_preferencias->getPref($user->id,$name);
			if($upref==NULL){
				$upref = new UserPreferencias();
				$upref->user_id = $user->id;
				$upref->name = $name;
				$upref->value = $value;
				$this->m_user_preferencias->create($upref);
			}else{
				$upref->value = $value;
				$this->m_user_preferencias->update($upref);
			}
		}catch(Exception $ex){
			$ret=array('ok'=>false,'msg'=>$ex->getMessage());
		}
		
		$this->returnJson($ret);
	}


	/*
	 * METODOS AUXILIARES
	 */

	private function getSerchedCahnnels($page,$search,$cant_per_page,$ceibal=0){
		$cant_pages = $this->m_channel->get_search_cantPages($search,$cant_per_page,$ceibal);
		if($page>$cant_pages){
			$page = $cant_pages;
		}
		
		$channels = ($page<1) ?  array() : ($this->m_channel->get_search_list($search,$page,$cant_per_page,$ceibal));

		$this->load->model("m_channel_thumb");
		foreach($channels as $c){
			$thumb = $this->m_channel_thumb->getRandThumb($c->suite_id);
			$c->thumb = $thumb->content;
		}
		return array(
			"page"=>$page,
			"cant_pages"=>$cant_pages,
			"channels"=>$channels
		);
	}

	//TODO hacer que se pueda borrar el canal de la siute si se desea hacer un rollback
	private function createChannelForUser(User $user){
		$xmltv_id = "U" . uniqid("", TRUE);
		$id=null;
		try{
			$this->load_api();
			//Se crea el canal en la suite
			$id = $this->api->create_channel_conf($user->suite_cert_cn, $xmltv_id,1,1,0);
		}catch(GoalbitServicesAPIException $error){
			throw new Exception("Error al tratar de crear el canal... " . $error->get_message());
		}

		//Channel
		$channel = new Channel();
		$channel->id			= $xmltv_id;
		$channel->suite_id		= $id;
		$channel->name			= 'Canal de Usuario';
		$channel->description           = 'Este canal es de usuario.';
		$channel->user_id		= $user->id;
		$channel->active		= true;
		$this->m_channel->create($channel);

		return $channel;
	}

}
